import * as Joi from '@hapi/joi';
import { print, printError } from './console-util';
import { throwJoiException } from './exception-util';

export function validate (schema: Joi.ObjectSchema, body, abortEarly = false, allowUnknown = true): any {
  const result = schema.validate(body, { abortEarly, allowUnknown });
  if (result.warning) {
    print(result.warning);
  }
  if (result.error) {
    print(result.error);
  }
  if (result.errors) {
    printError(result.errors);
  }

  if (!result.error && !result.errors) {
    return result.value;
  } else {
    throwJoiException(result);
  }
}